/*java jdk 1.7+
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''*/

package com.zxy.common;

import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES
{
	// 加密方式
	public static String	KEY_ALGORITHM	= "AES";
	// 数据填充方式
	String					algorithmStr	= "AES/CBC/PKCS7Padding";
	// 避免重复new生成多个BouncyCastleProvider对象，因为GC回收不了，会造成内存溢出
	// 只在第一次调用decrypt()方法时才new 对象
	public static boolean	initialized		= false;

	/**
	 * 
	 * @param originalContent
	 * @param encryptKey
	 * @param ivByte
	 * @return
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 */
	public static byte[] encrypt(byte[] originalContent, byte[] encryptKey, byte[] ivByte) throws Exception
	{
		// initialize();
		byte[] encrypted = null;
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec skeySpec = new SecretKeySpec(encryptKey,"AES");
		cipher.init(Cipher.ENCRYPT_MODE,skeySpec,new IvParameterSpec(ivByte));
		encrypted = cipher.doFinal(originalContent);
		return encrypted;
	}

	/**
	 * AES解密 填充模式AES/CBC/PKCS7Padding 解密模式128
	 * 
	 * @param content
	 *            目标密文
	 * @return
	 * @throws Exception
	 * @throws InvalidKeyException
	 * @throws NoSuchProviderException
	 */
	public static byte[] decrypt(byte[] content, byte[] aesKey, byte[] ivByte) throws Exception
	{
		// initialize();
		byte[] result = null;
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
		Key sKeySpec = new SecretKeySpec(aesKey,"AES");
		cipher.init(Cipher.DECRYPT_MODE,sKeySpec,generateIV(ivByte));// 初始化
		result = cipher.doFinal(content);
		return result;
	}

	/** BouncyCastle作为安全提供，防止我们加密解密时候因为jdk内置的不支持改模式运行报错。 **/
	// public static void initialize()
	// {
	// if(initialized)
	// return;
	// Security.addProvider(new BouncyCastleProvider());
	// initialized = true;
	// }

	// 生成iv
	public static AlgorithmParameters generateIV(byte[] iv) throws Exception
	{
		AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
		params.init(new IvParameterSpec(iv));
		return params;
	}
}
